<template>
  <div class="manage-products">
    <h2>Manage Products</h2>
    <!-- 添加/编辑商品表单 -->
    <div class="add-product-form">
      <el-form :model="currentProduct" label-width="120px">
        <el-form-item label="Product Name">
          <el-input v-model="currentProduct.name" placeholder="Enter product name" />
        </el-form-item>
        <el-form-item label="Product Price">
          <el-input v-model="currentProduct.price" type="number" placeholder="Enter product price" />
        </el-form-item>
        <el-form-item label="Product Stock">
          <el-input v-model="currentProduct.stock" type="number" placeholder="Enter product stock" />
        </el-form-item>
        <el-form-item label="Product Description">
          <el-input v-model="currentProduct.description" type="textarea" placeholder="Enter product description" />
        </el-form-item>
        <el-form-item label="Product Category">
          <el-radio-group v-model="currentProduct.category">
            <el-radio :value="'clothes'">Clothes</el-radio>
            <el-radio :value="'electronic'">Electronic</el-radio>
            <el-radio :value="'eating'">Eating</el-radio>
            <el-radio :value="'stationery'">Stationery</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Product Image">
          <el-input v-model="currentProduct.image" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item class="submit-button">
          <el-button v-if="isEditing" type="primary" @click="updateProduct" class="large-button">
            Update Product
          </el-button>
          <el-button v-else type="primary" @click="addProduct" class="large-button">Add Product</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <h2>Product List</h2>
      <div class="product-grid">
        <div v-for="product in products" :key="product.id" class="product-card">
          <div class="product-image" v-if="product.image">
            <img :src="product.image" alt="Product Image" />
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <p class="product-description">{{ product.description }}</p>
            <p class="product-price">￥{{ product.price }}</p>
            <p class="product-stock">Stock: {{ product.stock }}</p>
            <p class="product-category">Category: {{ product.category }}</p>
            <div class="product-actions">
              <el-button type="success" size="small" @click="editProduct(product)">Edit</el-button>
              <el-button type="danger" size="small" @click="deleteProduct(product)">Delete</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import { getSellerGoods, addGoods, updateGoods, deleteGoods } from '@/api/seller';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// import store from '@/store';
const st = useStore();
const router = useRouter();

// 响应式数据
const currentProduct = ref({
  id: null,
  name: '',
  price: 0,
  stock: 0,
  description: '',
  category: '',
  image: null,
});
const products = ref([]);
const isEditing = ref(false);
const loading = ref(false);

// 从 Vuex 获取商家名称
const sellername = computed(() => {
  const seller = st.getters['seller/sellername'];
  console.log('Current sellername from getter:', seller); // 添加调试日志
  return seller;
});

// 检查登录状态
const checkLoginStatus = () => {
  if (!sellername.value) {
    ElMessage.warning('请先登录商家账号');
    router.push('/login'); // 跳转到登录页
    return false;
  }
  return true;
};

// 获取商品列表
const fetchProducts = async () => {
  if (!checkLoginStatus()) return;
  
  loading.value = true;
  try {
    console.log('Fetching products for seller:', sellername.value); // 添加调试日志
    const response = await getSellerGoods(sellername.value);
    console.log('API Response:', response); // 添加调试日志
    
    if (response && response.code === 200) {
      products.value = response.data.map(item => ({
        id: item.goodsId,
        name: item.goodsName,
        price: item.price,
        stock: item.number,
        description: item.description,
        category: item.category,
        image: item.image,
        status: item.status,
        sellerName: item.sellerName
      }));
    } else {
      ElMessage.error(response?.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 添加商品
const addProduct = async () => {
  if (!checkLoginStatus()) return;
  
  if (!currentProduct.value.name || !currentProduct.value.price || !currentProduct.value.stock) {
    alert('请填写所有必填字段');
    return;
  }
  
  loading.value = true;
  try {
    const goodsData = {
      goodsName: currentProduct.value.name,
      price: currentProduct.value.price,
      number: currentProduct.value.stock,
      category: currentProduct.value.category,
      description: currentProduct.value.description,
      image: currentProduct.value.image,
      status: 1,
      sellerName: st.getters['seller/sellername']
      
    };
    console.log('Adding goods:', goodsData); // 添加调试日志
    const response = await addGoods(sellername.value, goodsData);
    if (response && response.code === 200) {
      alert('商品添加成功');
      resetForm();
      fetchProducts();
    } else {
      ElMessage.error(response?.msg || '商品添加失败');
    }
  } catch (error) {
    console.error('添加商品失败:', error);
    ElMessage.error('添加商品失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 编辑商品
const editProduct = (product) => {
  currentProduct.value = { ...product };
  isEditing.value = true;
};

// 更新商品
const updateProduct = async () => {
  if (!checkLoginStatus()) return;
  
  if (!currentProduct.value.name || !currentProduct.value.price || !currentProduct.value.stock) {
    ElMessage.warning('请填写所有必填字段');
    return;
  }
  
  loading.value = true;
  try {
    const goodsData = {
      goodsId: currentProduct.value.id,
      goodsName: currentProduct.value.name,
      price: Number(currentProduct.value.price),
      number: Number(currentProduct.value.stock),
      category: currentProduct.value.category,
      description: currentProduct.value.description,
      image: currentProduct.value.image,
      status: 1,
      sellerName: st.getters['seller/sellername']
    };
    
    console.log('准备更新的商品数据：', goodsData);
    const response = await updateGoods(goodsData);
    console.log('更新商品响应：', response);
//这边很奇怪，有时候有用有时候没用
    if (response && response.code === 200) {
      alert('商品更新成功');
      resetForm();
      fetchProducts();
    } else {
      ElMessage.error(response?.msg || '商品更新失败');
    }
  } catch (error) {
    console.error('更新商品失败:', error);
    ElMessage.error(error.response?.data?.msg || '更新商品失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 删除商品
const deleteProduct = async (product) => {
  if (!checkLoginStatus()) 
  
  {
    alert('请先登录商家账号');
    router.push('/userLogin');
  }
  
  loading.value = true;
  try {
    // const confirmResult = await ElMessageBox.confirm('确认删除该商品吗？', '提示', {
    //   confirmButtonText: '确定',
    //   cancelButtonText: '取消',
    //   type: 'warning'
    // });
    // if (confirmResult) {
      const response = await deleteGoods(sellername.value, product.id);
      if (response && response.code === 200) {
        alert('商品删除成功');
        ElMessage.success('商品删除成功');
        fetchProducts();
      } else {
        ElMessage.error(response?.msg || '商品删除失败');
      }
    // }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error);
      ElMessage.error('删除商品失败，请检查网络连接');
    }
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  currentProduct.value = {
    id: null,
    name: '',
    price: 0,
    stock: 0,
    description: '',
    category: '',
    image: null,
  };
  isEditing.value = false;
};

// 组件挂载时获取商品列表
onMounted(() => {
  if (sellername.value) {
    fetchProducts();
  } else {
    ElMessage.warning('请先登录商家账号');
    router.push('/login');
  }
});
</script>

<style scoped>
.manage-products {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #4caf50;
  font-size: 24px;
  margin-bottom: 20px;
}

.add-product-form {
  margin-bottom: 30px;
}

.el-form-item__label {
  font-size: 16px !important;
}

.el-input,
.el-textarea {
  font-size: 16px !important;
}

.submit-button {
  margin-top: 30px; /* 增加与上面内容的间距 */
  margin-left: 120px; /* 与 label-width 对齐 */
}

.large-button {
  width: 200px;
  height: 50px;
  font-size: 18px;
}

.upload-button {
  margin-top: 10px;
}

.product-list {
  margin-top: 20px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.product-image img {
  width: 100%;
  border-radius: 8px;
  margin-bottom: 10px;
}

.product-name {
  font-weight: bold;
  color: #333;
  margin: 10px 0 5px;
  font-size: 18px;
}

.product-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.product-price {
  color: #e91e63;
  font-weight: bold;
  font-size: 18px;
}

.product-stock {
  color: #4caf50;
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.el-button--success {
  background-color: #4caf50;
  border-color: #4caf50;
}

.el-button--success:hover {
  background-color: #66bb6a;
  border-color: #66bb6a;
}

.el-button--danger {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.el-button--danger:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.el-button--primary {
  background-color: #4caf50;
  border-color: #4caf50;
}

.el-button--primary:hover {
  background-color: #66bb6a;
  border-color: #66bb6a;
}
</style>